﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace IronWinter
{
    public class Camera
    {
        Viewport m_viewport;
        public Vector2 position, origin;
        public int X, Y, oX, oY;


        public Rectangle screenBounds
        {
            get { return new Rectangle(X, Y, m_viewport.Width, m_viewport.Height); }
        }

        public Camera(Viewport viewport)
        {
            m_viewport = viewport;
        }

        public void Move(Vector2 amount)
        {
            if (X + amount.X >= 0 && screenBounds.Right + amount.X <= Game1.currentMap.lvlWidth * Map.cellSize)
                X += (int)amount.X;
            
            if (Y + amount.Y >= 0 && screenBounds.Bottom + amount.Y - Game1.BAR_SIZE <= Game1.currentMap.lvlHeight * Map.cellSize)
                Y += (int)amount.Y;
        }

        public void LookAt(Unit target)
        {
            LookAt(target.Position);
        }

        public void LookAt(Vector2 coords)
        {
            Vector2 newPos = coords - new Vector2(m_viewport.Width / 2, m_viewport.Height / 2);

            if (newPos.X >= 0 && newPos.Y >= 0)
            {
                X = (int)newPos.X;
                Y = (int)newPos.Y;
            }
        }

        public Matrix GetViewMatrix()
        {
            // To add parallax, simply multiply it by the position
            return Matrix.CreateTranslation(new Vector3(-X, -Y, 0.0f));
        }

        public Vector2 WorldToScreen(Vector2 worldPosition)
        {
            return Vector2.Transform(worldPosition, GetViewMatrix());
        }

        public Vector2 ScreenToWorld(Vector2 screenPosition)
        {
            return Vector2.Transform(screenPosition, Matrix.Invert(GetViewMatrix()));
        }
    }
}
